import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutterapp/common/constant/api.dart';
import 'package:flutterapp/common/util/dialog_utils.dart';
import 'package:flutterapp/common/util/router_helpe_utils.dart';
import 'package:flutterapp/common/util/sp_utils.dart';
import 'package:flutterapp/common/util/event_bus_utils.dart';
import 'package:flutterapp/common/util/image_picker_utils.dart';
import 'package:flutterapp/common/util/toast_utils.dart';
import 'package:flutterapp/common/widget/myIcons.dart';
import 'package:flutterapp/http/http_utils.dart';
import 'package:flutterapp/me/page/about_soffware_page.dart';
import 'package:flutterapp/me/page/login_page.dart';
import 'package:flutterapp/me/page/update_theme_page.dart';
import 'package:flutterapp/me/service/me_service_impl.dart';
import 'package:image_picker/image_picker.dart';
import 'package:package_info_plus/package_info_plus.dart';

import 'page/my_favorite_page.dart';

class MePage extends StatefulWidget {
  ///标题
  final String? title;

  const MePage({Key? key, this.title}) : super(key: key);

  @override
  _MePageState createState() => _MePageState();
}

class _MePageState extends State<MePage> with AutomaticKeepAliveClientMixin {
  Image _backGroundImage = Image(
    image: AssetImage("images/lake.jpg"),
    fit: BoxFit.fill,
  );
  final picker = ImagePicker();

  //判断用户是否登录
  var isLogin = false;

  //用户名称
  var userName = "";

  //密码
  var password = "";

  //  记住密码
  var rememberPassword = false;

  late StreamSubscription loginSubscription;

  String? versionName;

  @override
  void initState() {
    super.initState();

    //添加监听
    initEvent();

    initData();
  }

  void initEvent() {
    //注册EventBus
    loginSubscription = EventBusUtils.instance.register((BusIEvent event) {
      if (event.busIEventID == BusIEventID.login_success) {
        initData();
      } else if (event.busIEventID == BusIEventID.logout_success) {
        initData();
      } else if (event.busIEventID == BusIEventID.update_head_back_ground) {
        setState(() {});
      }
    });
  }

  Future initData() async {
    isLogin = await SPUtils.getInstance().getIsLogin() ?? false;
    userName = await SPUtils.getInstance().getUserName() ?? '';
    password = await SPUtils.getInstance().getPassword() ?? '';
    rememberPassword =
        await SPUtils.getInstance().getRememberPassword() ?? false;

    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    bool haveUpdate = await MeServiceImpl.getInstance().checkNeedUpdate();
    versionName = "v${packageInfo.version}${haveUpdate ? "(有更新)" : ""}";
    setState(() {});
  }

  @override
  void dispose() {
    loginSubscription.cancel();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return Scaffold(
        body: NestedScrollView(
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
        return <Widget>[
          SliverAppBar(
            expandedHeight: 200.0,
            pinned: true,
            leading: IconButton(
              icon: Icon(
                Icons.account_circle,
                color: Colors.black,
                size: 30.0,
              ),
              onPressed: () async {
                //进入登录注册页面
                RouteHelpUtils.push(context, LoginPage());
              },
            ),
            flexibleSpace: FlexibleSpaceBar(
              title: GestureDetector(
                child: Text(isLogin ? userName : "点击登录/注册"),
                onTap: () async {
                  //已经登录,不做操作
                  if (isLogin) return;
                  //进入登录注册页面
                  RouteHelpUtils.push(context, LoginPage());
                },
              ),
              background: GestureDetector(
                child: _backGroundImage,
                onTap: () {
                  // getImage();
                  ImagePickerUtils.getInstance().showImagePickerDialog(context,
                      (image) {
                    _backGroundImage = image;
                    EventBusUtils.instance.fire(BusIEvent(
                        busIEventID: BusIEventID.update_head_back_ground));
                  }, showError: true);
                },
              ),
            ),
          )
        ];
      },
      body: SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            MeListItem(
              title: '我的收藏',
              leading: Icon(
                MyIcons.my_favorite,
                color: Theme.of(context).primaryColor,
              ),
              onTap: () async {
                //点击进入我的收藏页面(需要判断是否登录)
                if (isLogin) {
                  RouteHelpUtils.push(context, MyFavoritePage());
                } else {
                  //进入登录注册页面
                  RouteHelpUtils.push(context, LoginPage());
                }
              },
            ),
            MeListItem(
              title: '切换主题',
              leading: Icon(
                MyIcons.switch_theme,
                color: Theme.of(context).primaryColor,
              ),
              onTap: () {
                //切换主题
                RouteHelpUtils.push(context, UpdateThemePage());
              },
            ),
            MeListItem(
              title: '关于软件',
              leading: Icon(
                MyIcons.about_software,
                color: Theme.of(context).primaryColor,
              ),
              onTap: () {
                //关于软件
                RouteHelpUtils.push(context, AboutSoftwarePage());
              },
            ),
            MeListItem(
              title: '清理缓存',
              leading: Icon(
                MyIcons.clear_cache,
                color: Theme.of(context).primaryColor,
              ),
              onTap: () async {
                //清理缓存
                HttpUtils.getInstance().showProgressDialog(context, "清理中...");
                bool result = await HttpUtils.getInstance().clearAllCache();
                Navigator.pop(context);
                if (result) {
                  //清理成功
                  shortToast("清理成功");
                } else {
                  shortToast("清理失败");
                }
              },
            ),
            MeListItem(
              title: '检测更新',
              leading: Icon(
                MyIcons.check_update,
                color: Theme.of(context).primaryColor,
              ),
              subtitle: Text(versionName ?? ''),
              onTap: () {
                MeServiceImpl.getInstance().autoCheckUpdate(context);
              },
            ),
            Visibility(
              visible: isLogin,
              child: MeListItem(
                title: '退出登录',
                leading: Icon(
                  MyIcons.log_out,
                  color: Theme.of(context).primaryColor,
                ),
                onTap: () {
                  showEasyDialog(
                    context: context,
                    type: EasyDialogType.NormalTwoRowBtn,
                    content: '你确定退出登录?',
                    leftOrTopOnTap: (context) => Navigator.pop(context),
                    rightOrBottomOnTap: (context) {
                      Navigator.pop(context);
                      logout();
                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    ));
  }

  Future getImage() async {
    final pickedFile = await picker.pickImage(source: ImageSource.camera);
    setState(() {
      if (pickedFile != null) {
        _backGroundImage = Image.file(
          File(pickedFile.path),
          fit: BoxFit.fill,
        );
      } else {
        shortToast("No image selected.");
      }
    });
  }

  /// 退出登录操作
  void logout() {
    HttpUtils.getInstance().get(API.logout, onResult: (responses) {
      Map<String, dynamic> logoutBean = json.decode(responses.toString());
      if (logoutBean['errorCode'] == 0) {
        //退出成功
        //弹窗提示
        shortToast("退出成功");
        //重置本地数据状态
        SPUtils.getInstance().setValue(SPUtils.isLogin, false);
        if (!rememberPassword) {
//          SPUtils.getInstance().setValue(SPUtils.userName, "");
          SPUtils.getInstance().setValue(SPUtils.password, "");
        }

        //发出通知
        EventBusUtils.instance
            .fire(BusIEvent(busIEventID: BusIEventID.logout_success));
      } else {
        //退出失败
        shortToast(logoutBean['errorMsg'] ?? "退出失败");
      }
    }, onFailure: (error, stack) {
      shortToast(error.toString());
    });
  }

  @override
  bool get wantKeepAlive => true;
}

/// 列表的item组件
class MeListItem extends StatelessWidget {
  /// 左侧laeding组件
  final Widget? leading;

  /// 右侧laeding组件
  final Widget? subtitle;

  /// 标题
  final String title;

  /// item点击事件
  final void Function()? onTap;

  /// 是否显示底部的分割线
  final bool showBottomDivider;

  const MeListItem({
    Key? key,
    this.leading,
    required this.title,
    this.onTap,
    this.showBottomDivider = true,
    this.subtitle,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(mainAxisSize: MainAxisSize.min, children: [
        ListTile(
          leading: leading,
          trailing: subtitle,
          title: Text(title),
          onTap: onTap,
        ),
        Visibility(
          child: Container(
            color: Colors.grey,
            width: double.infinity,
            height: 0.5,
          ),
          visible: showBottomDivider,
        ),
      ]),
    );
  }
}

// class MeModel extends BaseModel {

//   Image _backGroundImage = Image(
//     image: AssetImage("images/lake.jpg"),
//     fit: BoxFit.fill,
//   );
//   final picker = ImagePicker();

//   //判断用户是否登录
//   var isLogin = false;

//   //用户名称
//   var userName = "";

//   //密码
//   var password = "";

//   //  记住密码
//   var rememberPassword = false;

//   late StreamSubscription loginSubscription;

//   String? versionName;


//   @override
//   Future<bool> init() {
//     return Future.value(true);
//   }
// }
